﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Utilities;

namespace SPDevLab.WebParts.JsAppWebPart.Apps
{
    public class AppPackage
    {
        #region contructors

        public AppPackage(SPFolder folder)
        {
            Init(folder);
        }

        #endregion

        #region properties

        private const string AppFileName = "app.htm";

        public string ServerRelativeUrl { get; set; }
        public string AppHtmlContent { get; set; }

        public Version Version { get; set; }

        #endregion

        #region methods

        private void Init(SPFolder folder)
        {
            ServerRelativeUrl = folder.ServerRelativeUrl;

            Version = new Version(folder.Name);
            AppHtmlContent = LoadAppContent(folder.ParentWeb, AppFileName);
        }

        private string LoadAppContent(SPWeb web, string folderRelativeUrl)
        {
            var appHtmlFile = web.GetFile(SPUrlUtility.CombineUrl(ServerRelativeUrl, folderRelativeUrl));

            if (appHtmlFile.Exists)
                return Encoding.UTF8.GetString(appHtmlFile.OpenBinary());

            return string.Empty;
        }

        #endregion
    }
}
